package com.qianjing.common.utils.bean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 实体转化基类
 * @author zhangzy
 * @version $Id: BaseConverter.java, v 0.1 2023/7/3 21:00 zhangzy Exp $
 */
public class BaseConverter<D,V> {

    private static final Logger LOGGER = LoggerFactory.getLogger(BaseConverter.class);

    public V convertDO2VO(D DO,Class<V> clazz){
        if(DO==null){
            return null;
        }
        V VO = null;
        try{
            VO = clazz.newInstance();
        }catch (Exception e){
            LOGGER.error("对象初始化出错{}->{}",DO.getClass(),VO.getClass());
        }
        convert(DO,VO,true);
        return VO;
    }

    public D convertVO2DO(V VO,Class<D> clazz){
        if(VO==null){
            return null;
        }
        D DO = null;
        try{
            DO = clazz.newInstance();
        }catch (Exception e){
            LOGGER.error("对象初始化出错{}->{}",VO.getClass(),DO.getClass());
        }
        convert(DO,VO,false);
        return DO;
    }

    public List<D> converterVOs2DOs(List<V> vList,Class<D> clazz){
        if (CollectionUtils.isEmpty(vList)) {
            return new ArrayList<D>();
        }
        List<D> dList = new ArrayList<D>();

        for(V v : vList){
            dList.add(convertVO2DO(v,clazz));
        }
        return dList;
    }

    public List<V> converterDOs2VOs(List<D> dList,Class<V> clazz){
        if (CollectionUtils.isEmpty(dList)) {
            return new ArrayList<V>();
        }
        List<V> vList = new ArrayList<V>();

        for(D d : dList){
            vList.add(convertDO2VO(d,clazz));
        }
        return vList;
    }

    /**
     * 属性拷贝方法，有特殊需求时子类覆写此方法,将不同的属性值自定义设置
     */
    protected void convert(D from, V to,boolean flag) {
        if(flag){
            BeanUtils.copyProperties(from, to);
        }else {
        	BeanUtils.copyProperties(to, from);
        }
    }
}
